package com.ykt.service;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.ykt.common.utils.page.PageData;
import com.ykt.common.utils.page.PageParam;
import com.ykt.model.User;
import com.ykt.model.UserCollect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 收藏服务
 */
public class UserCollectService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserCollectService.class);

    private User userDao = User.dao;
    private UserCollect userCollectDao = UserCollect.dao;

    /**
     * 根据USERID查询所有收藏
     * @param param userId 和 分页参数
     * @return 地址信息
     */
    public PageData<UserCollect> findByUserId(PageParam<Integer> param){
        PageData<UserCollect> pd = userCollectDao.pageFindByUserId(param);
        if(pd == null || pd.getPageData() == null || pd.getPageData().isEmpty()){
            return pd;
        }

        List<Integer> ids = new ArrayList<>();
        for (UserCollect entity : pd.getPageData()) {

            Integer merchantId = entity.getInt("merchantId");
            if(merchantId != null && !ids.contains(merchantId)){
                ids.add(merchantId);
            }
        }

        List<User> users = userDao.findByIds(ids);
        if(users == null || users.isEmpty()){
            return pd;
        }

        Map<Integer, User> userMap = new HashMap<>();
        for (User entity : users) {
            userMap.put(entity.getInt(User.id), entity);
        }

        for (UserCollect entity : pd.getPageData()) {
            Integer merchantId = entity.getInt("merchantId");
            if(merchantId != null){
                User user = userMap.get(merchantId);
                if(user == null){
                    continue;
                }

                entity.put("merchantName", user.get(User.name));
                entity.put("merchantHead", user.get(User.head));
            }
        }

        return pd; // 因为引用无需再设置到pd变量中
    }
    
    public UserCollect find(Integer userId, Integer shopId){
    	return userCollectDao.find(userId, shopId);
    }

    @Before(Tx.class)
    public boolean delete(final Integer userId, final Integer shopId){
        return userCollectDao.delete(userId, shopId);
    }

    @Before(Tx.class)
    public boolean save(UserCollect userCollect){
        return userCollect.save();//直接保存即可
    }
}
